package com.binarysoft.cmdhandler.id;

import java.util.Collection;
import java.util.StringTokenizer;

import com.binarysoft.service.id.IDService;

import common.framework.command.handler.AbstractCommandHandler;
import common.framework.command.server.Terminal;
import common.framework.dsb.annotation.DSBCmd;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;

@DSBCmd("id")
public class IDCmdHandler extends AbstractCommandHandler {

	@Override
	public void handle(String args, Terminal terminal) throws Exception {
		terminal.println("");
		StringTokenizer stier = new StringTokenizer(args);
		int count = stier.countTokens();
		if (count < 3) {
			terminal.println(" id ls cache                     --print cached IDs (ready to be used) in pool.");
			terminal.println(" id ls next                      --print and consume next ID in ID pool.");
			terminal.println("");
			return;
		}
		stier.nextToken();
		String cmd1 = stier.nextToken();
		String cmd2 = stier.nextToken();
		if ("ls".equalsIgnoreCase(cmd1) && "cache".equalsIgnoreCase(cmd2)) {
			listCachedIDs(terminal);
		} else if ("ls".equalsIgnoreCase(cmd1) && "next".equalsIgnoreCase(cmd2)) {
			nextID(terminal);
		} else {
			terminal.println(" id ls cache                     --print cached IDs (ready to be used) in pool.");
			terminal.println(" id ls next                      --print and consume next ID in ID pool.");
		}
		terminal.println("");
	}// handle

	private void listCachedIDs(Terminal terminal) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		IDService idService = serviceFactory.lookup("DSB/IDService");
		Collection<Long> result = idService.getCacheIDs();
		int n = 0;
		for (Long lo : result) {
			n++;
			terminal.print("\t" + lo);
			if (n % 10 == 0) {
				terminal.println("");
			}
		}
		terminal.println("");
		terminal.println("Total cached IDs: " + n + " .");
	}

	private void nextID(Terminal terminal) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		IDService idService = serviceFactory.lookup("DSB/IDService");
		long id = idService.nextID();
		terminal.println(" Next ID: " + id);
	}
}
